import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_address_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/binding_terminal_view_model.dart';
import 'package:e_reception_flutter/utils/address_about_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'add_channel_org_page.dart';
import 'channel_org_list_view_model.dart';

class ChannelOrgListPage extends StatefulWidget{

  static const String ROUTER = "ChannelOrgListPage";

  final String gps;
  final String cbid;
  final CompanyAddressListInfoBean addressBean;
  final Function(String cbid) onSetCbid;
  const ChannelOrgListPage({Key key, this.gps, this.addressBean, this.cbid, this.onSetCbid}) : super(key: key);

  @override
  _ChannelOrgListPageState createState() => _ChannelOrgListPageState();

  static Future<CompanyAddressListInfoBean> navigatorPush(BuildContext context,
      String gps, CompanyAddressListInfoBean addressBean, {String cbid, Function onSetCbid}) {
    return RouterUtils.routeForFutureResult(
      context,
      ChannelOrgListPage(
          gps:gps,
          addressBean:addressBean,
          cbid:cbid,
        onSetCbid:onSetCbid,
      ),
      routeName: ChannelOrgListPage.ROUTER,
    );
  }

}

class _ChannelOrgListPageState extends BasePagerState<CompanyAddressListInfoBean, ChannelOrgListPage>
    with VgPlaceHolderStatusMixin{
  ChannelOrgListViewModel _viewModel;
  BindingTerminalViewModel _bindingViewModel;
  String _gps;
  CompanyAddressListInfoBean _currentAddress;
  TextEditingController _positionController;
  TextEditingController _backupController;
  @override
  void initState() {
    super.initState();
    _positionController = TextEditingController();
    _backupController = TextEditingController();
    _gps = widget?.gps??"";
    _viewModel = ChannelOrgListViewModel(this, gps: _gps);
    _bindingViewModel = BindingTerminalViewModel(this,);
    _viewModel.refresh();
    if((widget?.addressBean??null) != null){
      _currentAddress = widget?.addressBean;
    }else if(StringUtils.isNotEmpty(widget?.cbid)){
      _currentAddress = CompanyAddressListInfoBean();
      _currentAddress.cbid = widget?.cbid;
    }

  }

  @override
  void dispose() {
    _positionController?.dispose();
    _backupController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          children: [
            _toTopBarWidget(),
            // _toPlaceHolderWidget(),
            Expanded(child: _toPlaceHolderWidget()),
          ],
        ),
      ),
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "所属地址",
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  Widget _toPlaceHolderWidget(){
    return Stack(
      children: [
        VgPlaceHolderStatusWidget(
          errorOnClick: () => _viewModel?.refresh(),
          emptyOnClick: () => _viewModel?.refresh(),
          loadingStatus: data == null,
          child:_toListParentWidget(),
        ),
        Visibility(
          visible: VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId()),
          child: Align(
            alignment: Alignment.bottomCenter,
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: ()async{
                bool result = await AddChannelOrgPage.navigatorPush(context, widget?.gps, () { });
                if(result != null && result){
                  _viewModel.refresh();
                }
              },
              child: Container(
                alignment: Alignment.center,
                width: 140,
                height: 40,
                margin: const EdgeInsets.only(bottom: 50),
                decoration: BoxDecoration(
                  color: Color(0xFF1890FF),
                  borderRadius: BorderRadius.circular(24),
                ),
                child: Center(
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Image.asset("images/icon_add_channel_org.png", width: 14, color: Colors.white,),
                      SizedBox(width: 4,),
                      Text(
                        "添加地址",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 15,
                            height: 1.2,
                            fontWeight: FontWeight.w600
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget _toListParentWidget() {
    return VgPullRefreshWidget.bind(
        state: this,
        viewModel: _viewModel,
        child: _toListWidget());
  }

  Widget _toListWidget() {
    return ListView.separated(
        itemCount: data?.length ?? 0,
        padding: const EdgeInsets.all(0),
        physics: BouncingScrollPhysics(),
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        itemBuilder: (BuildContext context, int index) {
          return _toListItemWidget(context, index, data?.elementAt(index));
        },
        separatorBuilder: (BuildContext context, int index) {
          return SizedBox(height: 0);
        });
  }

  Widget _toListItemWidget(BuildContext context, int index, CompanyAddressListInfoBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        if(itemBean.cbid == _currentAddress?.cbid){
          RouterUtils.pop(context, result: new CompanyAddressListInfoBean());
        }else{
          bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
              title: "提示", content: "确认修改设备所属地址？",
            cancelText: "取消",
            confirmText: "确定",);
          if (result ?? false) {
            if(StringUtils.isNotEmpty(widget?.cbid??"") || widget?.onSetCbid != null){
              RouterUtils.pop(context, result: itemBean);
              widget?.onSetCbid?.call(itemBean.cbid);
            }else{
              RouterUtils.pop(context, result: itemBean);
            }
          }

        }

      },
      child: Container(
        alignment: Alignment.centerLeft,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        padding: EdgeInsets.symmetric(horizontal: 15,),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 12,),
            Text(
              itemBean?.branchname??"暂无机构名",
              textAlign: TextAlign.start,
              softWrap: true,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                  fontSize: 14,
                  color: (itemBean.cbid == _currentAddress?.cbid)?ThemeRepository.getInstance().getPrimaryColor_1890FF()
                      :ThemeRepository.getInstance().getTextColor_D0E0F7(),
                  height: 1.2
              ),
            ),
            SizedBox(height: 3,),
            Text(
              AddressAboutUtils.getAddressSplicing(itemBean),
              softWrap: true,
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.start,
              style: TextStyle(
                  fontSize: 12,
                  color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                  height: 1.2
              ),
            ),
            SizedBox(height: 12,),
          ],
        ),
      ),
    );
  }

}